<template>
  <div class="app-container">
    <div v-show="!detailInfo.visible && !detailListInfo.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :slipSelectRequest="slipSelectRequest"
          :clearType="clearType"
        >
        </new-page-filter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-authorize>
            <el-button :disabled="!canAuthorize" @click="audit()"
              >批准</el-button
            >
          </template>
        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
        <template v-slot:col-useOrderNo="scope">
          <span>{{ scope.row.useApplication.orderNo }}</span>
        </template>
      </table-container>
    </div>
    <!-- 明细 -->
    <audit-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :title="detailInfo.title"
      :id="detailInfo.id"
      @returnBack="getList"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
  </div>
</template>

<script setup name="useReturnAudit">
import {
  getUseReturnApplicationCustomizeList,
  reverseAuditUseApplication,
  rejectUseReturnApplication,
  exportAuditUseApplication,
} from '@/api/use.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import AuditDetail from './details'
const detailList = defineAsyncComponent(() => import('./detailList'))

const { proxy } = getCurrentInstance()

// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    queryMap: {
      depotIdAuth: {
        asTbName: 'use_return_application_order',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'OR',
        value: 'depotAuth',
      },
      storeDeptIdAuth: {
        asTbName: 'use_return_application_order',
        columnName: 'store_depot_id',
        queryType: 'IN',
        queryCategory: 'OR',
        value: 'depotAuth',
      },
    },
    customizeUserVO: {},
    queryParams: {
      status: [2, 3, 9],
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'slot',
      value: 'authorize',
      show: proxy.$permission('useReturnAudit:authorize'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  selections: [],
  data: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '批准',
        event: audit,
        show: proxy.$permission('useReturnAudit:authorize'),
        ifRender(row) {
          return row.status === 2
        },
      },
      {
        label: '驳回',
        event: reject,
        show: proxy.$permission('useReturnAudit:reject'),
        ifRender(row) {
          return row.status === 2 || row.status === 3
        },
      },
      {
        label: '生成出库单',
        event: exportHandle,
        show: proxy.$permission('useReturnAudit:export'),
        ifRender(row) {
          return row.status === 3
        },
      },
    ],
  },
})
const selectRows = ref([])
const detailInfo = ref({
  visible: false,
  title: '',
  id: '',
})
const modifyInfo = ref({
  visible: false,
  title: '',
  returnStoreId: '',
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)

const canAuthorize = computed(() => {
  return (
    tableInfo.value.selections.length &&
    tableInfo.value.selections.filter((row) => row.status !== 2).length === 0
  )
})

setData()
function setData() {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'use_return_audit_status',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let _filterInfo = filterInfo.value
  let arr = [
    {
      asTbName: 'use_return_application_order',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
  ]
  _filterInfo.query.queryMap = {}
  _filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  _filterInfo.query.queryMap = proxy.$fn.deepClone(_filterInfo.copyQueryMap)
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.id = row.id
  detailInfo.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function getIds(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((row) => row.id)
  }
  return ids
}
//批准
function audit(row = undefined) {
  const ids = getIds(row)
  reverseAuditUseApplication(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//生成出库单
function exportHandle(row = undefined) {
  const ids = getIds(row)
  exportAuditUseApplication(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//驳回，其实和撤回是同样的效果
function reject(row = undefined) {
  proxy
    .$prompt('驳回理由', '领用审核', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^[\S]+/,
      inputErrorMessage: '请输入驳回理由',
    })
    .then(({ value }) => {
      let param = {}
      param.ids = [row.id]
      param.remark = value
      rejectUseReturnApplication(param).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
}
//驳回，其实和撤回是同样的效果
function rejectSelect() {
  if (selectRows.value.length != 0) {
    let firstStatus = 2
    let isOnly = true
    selectRows.value.forEach((row) => {
      if (firstStatus != row.status) {
        isOnly = false
        return
      }
    })
    if (!isOnly) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '只能选择状态为【待审核】的数据',
      })
      return
    }
    const ids = selectRows.value.map((row) => row.id)
    rejectUseReturnApplication(ids).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
  } else {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请选择一条操作数据',
    })
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = {
    tableKey:
      'useReturnApplicationOrderRatifyIndex-com.slip.spd.entity.vo.use.UseReturnApplicationOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      )
      _filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ..._filterInfo.query.queryMap,
      }
      _filterInfo.searchList = searchInfo.searchList
      _filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      _tableInfo.api = getUseReturnApplicationCustomizeList
      getList()
    }
  })
}
function sortChange(column) {
  let _filterInfo = filterInfo.value
  if (_filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, _filterInfo.sortArr)
    _filterInfo.sortArr = arr
    _filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
